package com.madixin.chat.controller;

import com.madixin.chat.constants.Constants;
import com.madixin.chat.exception.ChatBaseException;
import com.madixin.chat.exception.ErrorCode;
import com.madixin.chat.model.ChatMessage;
import com.madixin.chat.model.ChatSession;
import com.madixin.chat.security.LoginUserDetails;
import com.madixin.chat.service.impl.ChatMessageService;
import com.madixin.chat.service.impl.ChatSessionService;
import io.swagger.v3.oas.annotations.Operation;
import io.swagger.v3.oas.annotations.security.SecurityRequirement;
import io.swagger.v3.oas.annotations.tags.Tag;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.core.context.SecurityContextHolder;
import org.springframework.web.bind.annotation.*;
import com.madixin.chat.dto.ResponseResult;

import java.util.List;

@RestController
@SecurityRequirement(name = "BearerAuth")
@RequestMapping(value = "/chatsession")
@Tag(name = "聊天对话Session接口")
public class ChatSessionController {

    @Autowired
    private ChatSessionService chatSessionService;

    @Autowired
    private ChatMessageService chatMessageService;

    @Operation(summary = "创建新的对话")
    @PostMapping("/")
    public ResponseResult<ChatSession> createSession(@RequestBody ChatSession chatSession) throws ChatBaseException {
        if (StringUtils.isBlank(chatSession.getTitle())){
            return ResponseResult.fail("Invalid title", ErrorCode.ILLEGAL_PARAM);
        }
        if (chatSession.getTitle().length() > Constants.SESSION_TITLE_MAXSIZE) {
            chatSession.setTitle(chatSession.getTitle().substring(0, Constants.SESSION_TITLE_MAXSIZE));
        }

        LoginUserDetails loginUser = (LoginUserDetails) SecurityContextHolder.getContext().getAuthentication().getPrincipal();
        chatSession.setUserId(loginUser.getUser().getId());
        chatSessionService.createSession(chatSession);
        return ResponseResult.success(chatSession);
    }

    @Operation(summary = "删除对话")
    @DeleteMapping("/{sessionId}")
    public ResponseResult<String> deleteSession(@PathVariable("sessionId") String sessionId) throws ChatBaseException  {
        if (StringUtils.isBlank(sessionId) || sessionId.length() != Constants.UUID_SIZE) {
            return ResponseResult.fail("Invalid sessionId", ErrorCode.ILLEGAL_PARAM);
        }

        // 1.根据sessionId查询会话信息，如果不存在，返回成功
        ChatSession chatSession = chatSessionService.getSessionById(sessionId);
        if (chatSession == null){
            return ResponseResult.success("");
        }

        // 2.判断会话是否属于当前用户，如果不是，则提示无权限
        LoginUserDetails loginUser = (LoginUserDetails) SecurityContextHolder.getContext().getAuthentication().getPrincipal();
        if (!StringUtils.equals(loginUser.getUser().getId(), chatSession.getUserId())){
            return ResponseResult.fail(ErrorCode.ILLEGAL_PERMISSION);
        }

        // 3.删除会话
        chatSessionService.deleteSession(sessionId);

        return ResponseResult.success("");
    }

    @Operation(summary = "更新对话")
    @PutMapping("/{sessionId}")
    public ResponseResult<String> updateSession(@PathVariable("sessionId") String sessionId,@RequestBody ChatSession updateSession) throws ChatBaseException {
        if (StringUtils.isBlank(sessionId) || sessionId.length() != Constants.UUID_SIZE) {
            return ResponseResult.fail("Invalid sessionId", ErrorCode.ILLEGAL_PARAM);
        }
        if (StringUtils.isBlank(updateSession.getTitle())){
            return ResponseResult.fail("Invalid title", ErrorCode.ILLEGAL_PARAM);
        }
        if (updateSession.getTitle().length() > Constants.SESSION_TITLE_MAXSIZE) {
            updateSession.setTitle(updateSession.getTitle().substring(0, Constants.SESSION_TITLE_MAXSIZE));
        }

        // 1.根据sessionId查询会话信息，如果不存在，返回成功
        ChatSession chatSession = chatSessionService.getSessionById(sessionId);
        if (chatSession == null){
            return ResponseResult.success("");
        }

        // 2.判断会话是否属于当前用户，如果不是，则提示无权限
        LoginUserDetails loginUser = (LoginUserDetails) SecurityContextHolder.getContext().getAuthentication().getPrincipal();
        if (!StringUtils.equals(loginUser.getUser().getId(), chatSession.getUserId())){
            return ResponseResult.fail(ErrorCode.ILLEGAL_PERMISSION);
        }

        // 3.更新会话
        chatSession.setTitle(updateSession.getTitle());
        chatSessionService.updateSession(chatSession);


        return ResponseResult.success("");
    }

    @Operation(summary = "获取当前用户的会话")
    @GetMapping("")
    public ResponseResult<List<ChatSession>> getUserSessions(
            @RequestParam(defaultValue = "0") int page,
            @RequestParam(defaultValue = "10") int size) throws ChatBaseException {
        LoginUserDetails loginUser = (LoginUserDetails) SecurityContextHolder.getContext().getAuthentication().getPrincipal();

        return ResponseResult.success(chatSessionService.getUserSessions(loginUser.getUser().getId(),page,size));
    }

    @Operation(summary = "获取当前会话的上下文")
    @GetMapping("/{sessionId}/message")
    public ResponseResult<List<ChatMessage>> getConversationMessage(
            @PathVariable("sessionId") String sessionId,
            @RequestParam(defaultValue = "0") int page,
            @RequestParam(defaultValue = "10") int size) throws ChatBaseException {
        if (StringUtils.isBlank(sessionId) || sessionId.length() != Constants.UUID_SIZE) {
            return ResponseResult.fail("Invalid sessionId", ErrorCode.ILLEGAL_PARAM);
        }

        // 1.根据sessionId查询会话信息，如果不存在，抛出异常
        ChatSession chatSession = chatSessionService.getSessionById(sessionId);
        if (chatSession == null){
            throw new ChatBaseException(ErrorCode.FAIL_GET_SESSION_MESSAGE);
        }

        // 2.判断会话是否属于当前用户，如果不是，则提示无权限
        LoginUserDetails loginUser = (LoginUserDetails) SecurityContextHolder.getContext().getAuthentication().getPrincipal();
        if (!StringUtils.equals(loginUser.getUser().getId(), chatSession.getUserId())){
            return ResponseResult.fail(ErrorCode.ILLEGAL_PERMISSION);
        }

        return ResponseResult.success(chatMessageService.getConversationMessage(sessionId, page, size));
    }
}
